from django.db import models
from django.contrib.auth.models import User

class DocumentCategory(models.Model):
    name = models.CharField('分类名称', max_length=100)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, verbose_name='父分类')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '文档分类'
        verbose_name_plural = '文档分类'

    def __str__(self):
        return self.name

class Document(models.Model):
    DOCUMENT_STATUS = (
        ('draft', '草稿'),
        ('published', '已发布'),
        ('archived', '已归档'),
    )

    title = models.CharField('文档标题', max_length=200)
    content = models.TextField('文档内容', blank=True)
    file = models.FileField('文件', upload_to='documents/%Y/%m/%d/', blank=True, null=True)
    category = models.ForeignKey(DocumentCategory, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='分类')
    status = models.CharField('状态', max_length=20, choices=DOCUMENT_STATUS, default='draft')
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='created_documents', verbose_name='创建人', null=True, blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    tags = models.CharField('标签', max_length=255, blank=True)
    description = models.TextField('描述', blank=True)

    class Meta:
        verbose_name = '文档'
        verbose_name_plural = '文档'
        db_table = 'doc_manager_document'
        ordering = ['-created_at']

    def __str__(self):
        return self.title

class DocumentVersion(models.Model):
    document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='versions')
    version_number = models.PositiveIntegerField('版本号')
    file = models.FileField('文件', upload_to='document_versions/%Y/%m/%d/')
    changes = models.TextField('变更说明', blank=True)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='创建人')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '文档版本'
        verbose_name_plural = '文档版本'
        ordering = ['-created_at']
        unique_together = ('document', 'version_number')

    def __str__(self):
        return f"{self.document.title} - 版本{self.version_number}"
